define(['app'], function (app) {
  app.registerController(
    'BaseUsersCtrl1',
    ['$scope', '$state', '$stateParams', 'PageData', 'Common', function ($scope, $state, $stateParams, PageData, Common) {
      console.log('loaded BaseUsersCtrl');
      PageData.title = "用户";
      $scope.query = {};
      $scope.limit = 10;
      $scope.offset = 0;
      $scope.count = 0;
      var model;
      model = Common('User', {}, false);

      $scope.search = function () {
        model.query({
          query: $scope.query, limit: $scope.limit, offset: $scope.offset
        }, function (response) {
          $scope.list = response.rows;
          $scope.count = response.count;
        }, function (error) {
          console.log(error);
        });
      };
      $scope.previous = function () {
        if ($scope.offset >= $scope.limit) {
          $scope.offset = $scope.offset - $scope.limit;
          $scope.search();
        }
      };
      $scope.next = function () {
        var last = $scope.count - $scope.offset;
        $scope.offset = $scope.offset + (last > $scope.limit ? $scope.limit : last);
        $scope.search();
      };
      $scope.refresh = function () {
        $scope.search();
      };
      var id = $stateParams.id;
      console.log(id);
      if (id) {
        model.get({id: id}, function (res) {
          $scope.formData = res;
        });
      } else {
        $scope.formData = {};
        $scope.search();
      }
      $scope.select = function (id) {
        $scope.item = model.get({id: id});
      };
      $scope.toggle = function (checkAll,list) {
        _.each(list, function (item) {
          item.ck = checkAll;
        });
      };

      $scope.add = function () {
        $('#userModal').modal({});
      };
      $scope.delete = function (ids, online) {
        if (!ids || ids.length == 0) {
          ids = []
          _.forEach($scope.list, function (item) {
            if (item.ck) {
              ids.push(item.id);
            }
          });
        }
        model.delete({ids: ids}, function (res) {
          console.log(res);
          $state.go('app.base.users.list');
          $scope.refresh();
        });
      };
      $scope.onAddSubmit = function () {
        if ($scope.formData.id) {
          Common('User', {id: $scope.formData.id}, false).update($scope.formData, function () {
            $state.go('app.base.users.list');
            $scope.refresh();
          });
        } else {
          model.save($scope.formData, function () {
            $state.go('app.base.users.list');
            $scope.refresh();
          });
        }
      }
    }]
  );
});
